import { useEffect, useRef } from 'react'
import { useAuth } from '@/contexts/AuthContext'
import { useNavigate, useLocation } from '@tanstack/react-router'

interface ProtectedRouteProps {
  children: React.ReactNode
}

export function ProtectedRoute({ children }: ProtectedRouteProps) {
  const { isAuthenticated, isLoading } = useAuth()
  const navigate = useNavigate()
  const location = useLocation()
  const hasRedirected = useRef(false)

  useEffect(() => {
    if (!isLoading && !isAuthenticated && !hasRedirected.current) {
      // 只有当前不在登录页面时才重定向
      if (location.pathname !== '/login') {
        hasRedirected.current = true
        navigate({ 
          to: '/login',
          replace: true,
        })
      }
    }
    
    // 如果用户已登录，重置重定向标志
    if (isAuthenticated) {
      hasRedirected.current = false
    }
  }, [isAuthenticated, isLoading, navigate, location.pathname])

  // 如果正在加载认证状态，显示加载页面
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600 dark:text-gray-400">正在验证用户身份...</p>
        </div>
      </div>
    )
  }

  // 如果用户未登录，不渲染任何内容（因为已经在useEffect中处理了重定向）
  if (!isAuthenticated) {
    return null
  }

  // 用户已登录，渲染子组件
  return <>{children}</>
}
